
define(['ionic', 'services'], function () {
    angular.module('U9Mobile.services')
        .factory('UserService', ['$rootScope', '$http', '$q', 'ConnectService', 'UtilService', 'OperaterUtil', 'FileStorage', 'AppConstants',
            function ($rootScope, $http, $q, ConnectService, UtilService, OperaterUtil, FileStorage, AppConstants) {
                var userInfo = {},
                    user = {
                        logined: false,
                        access_token: '',
                        user_alias: ''
                    },
                    detailInfo;

                var userDefer = $q.defer(),
                    o = {
                        loginPromise: userDefer.promise
                    };

                FileStorage.loadingPromise.then(function () {
                    userInfo = {
                        account: FileStorage.get('account', ''),
                        password: FileStorage.get('password', ''),
                        org: FileStorage.get('org', {}),
                        autologin: FileStorage.get('autologin', false),
                        rememberpsw: FileStorage.get('rememberpsw', false)
                    };
                    if (userInfo.autologin) {
                        o.login(userInfo).then(function () {

                            userDefer.resolve(userInfo);
                        }, function () {
                            userDefer.resolve(userInfo);
                        });
                    } else {
                        userDefer.resolve(userInfo);
                    }
                });

                o.getOrgList = function (account) {
                    var defer = $q.defer();

                    var url = AppConstants.GET_ORG_URL.format({
                        address: ConnectService.getConnect('address'),
                        port: ConnectService.getConnect('port'),
                        account: account || userInfo.account,
                        company: ConnectService.getConnect('company')
                    });
                    $http({
                        method: 'post',
                        url: url,
                        timeout: AppConstants.HTTP_TIME_OUT
                    }).success(function (data) {
                        defer.resolve(data.organizations);
                    }).error(function () {
                        defer.reject();
                    });

                    return defer.promise;
                };
                o.setOrg = function (org) {
                    userInfo.org = org;

                    return FileStorage.set('org', org);
                };
                o.getOrg = function () {
                    return userInfo.org;
                };
                o.login = function (obj) {
                    var defer = $q.defer();

                    var url = AppConstants.LOGIN_URL.format({
                        address: ConnectService.getConnect('address'),
                        port: ConnectService.getConnect('port')
                    });
                    $http({
                        method: 'get',
                        url: url,
                        params: {
                            enterprise_id: ConnectService.getConnect('company'),
                            user_code: obj.account,
                            organization_id: '',
                            password: obj.password
                        },
                        timeout: AppConstants.HTTP_TIME_OUT
                    }).success(function (data) {
                        if (data.status_code === "200" && data.access_token) {
                            user.access_token = data.access_token;
                            user.user_alias = data.user_alias;
                            user.logined = true;

                            var save = {
                                account: obj.account
                            };
                            if (obj.rememberpsw) {
                                save.password = obj.password;
                            } else {
                                save.password = '';
                            }
                            o.setUserParams(save).then(function () {
                                $q.all([maybeUpdateComapnyOrg(data), updateUserDetailInfo(obj.account)]).finally(function () {
                                    $rootScope.$broadcast('login');
                                    defer.resolve(data);
                                });
                            });
                        } else {
                            user.logined = false;
                            defer.resolve(data);
                        }
                    }).error(function (error) {
                        user.logined = false;
                        defer.reject(error);
                    });

                    return defer.promise;
                };
                o.logout = function () {
                    user.logined = false;
                    user.access_token = '';
                    user.user_alias = '';
                    detailInfo = {};
                    if (!userInfo.rememberpsw) {
                        o.setUserParams({
                            password: ''
                        });
                    }
                    $rootScope.$broadcast('logout');
                };
                o.setUserParams = function (key, value) {
                    var defer = $q.defer();

                    if (angular.isString(key)) {
                        userInfo[key] = value;
                    } else if (angular.isObject(key)) {
                        angular.extend(userInfo, key);
                    }
                    FileStorage.set(key, value).finally(function () {
                        defer.resolve();
                    });

                    return defer.promise;
                };
                o.getUserParams = function (key) {
                    return userInfo.hasOwnProperty(key) ? userInfo[key] : null;
                };
                o.getUserToken = function () {
                    return {
                        logined: user.logined,
                        access_token: user.access_token,
                        user_alias: user.user_alias
                    };
                };
                o.getPushConfig=function(){
                    return {
                        user_code: userInfo.account,
                        enterprise_id: ConnectService.getConnect('company')
                    }
                };
                o.getUserDetailInfo = function () {
                    return angular.copy(detailInfo);
                };

                return o;

                function maybeUpdateComapnyOrg(data) {
                    var defer = $q.defer();

                    ConnectService.setConnectParam('company', data.enterprise).finally(function () {
                        $q.when(
                            data.organizationCode === '' ? true : o.setOrg({
                                id: data.organizationId,
                                code: data.organizationCode,
                                name: data.organizationName
                            })
                        ).finally(function () {
                            defer.resolve();
                        });
                    });

                    return defer.promise;
                }
                function updateUserDetailInfo(account) {
                    var defer = $q.defer();

                    OperaterUtil.queryPersonInfo().then(function (result) {
                        if (!angular.isObject(result)) {
                            detailInfo = {
                                name: '未取到联系对象'
                            };
                            defer.resolve();
                        } else {
                            if (!result.Code) {
                                detailInfo = {
                                    name: '未取到联系对象'
                                };
                                defer.resolve();
                            } else {
                                if (result.MobilNum && result.MobilNum[0] === '-') {
                                    result.MobilNum = result.MobilNum.substr(1);
                                }
                                detailInfo = {
                                    id: result.ID,
                                    name: result.Name,
                                    company: result.Company ? result.Company : '',
                                    department: result.Dept,
                                    postion: result.Job,
                                    code: result.Code,
                                    tel: result.MobilNum,
                                    phone: result.Phone,
                                    mail: result.Email
                                };
                                if (result.Seal) {
                                    detailInfo.photo = 'data:image/png;base64,' + result.Seal;
                                }
                                defer.resolve(detailInfo);
                            }
                        }
                    }, function () {
                        detailInfo = {
                            name: '未取到联系对象'
                        };
                        defer.resolve();
                    });

                    return defer.promise;
                }
            }
        ]);
});